/**
 * @param {number[][]} image
 * @param {number} sr
 * @param {number} sc
 * @param {number} color
 * @return {number[][]}
 */
var floodFill = function(image, sr, sc, color) {
  let record = image[sr][sc], direction = [[0, 1], [1, 0], [0, -1], [-1, 0]];
  if(record == color) return image;
  function isValid(i, j) {
    return (i >= 0 && i < image.length) && (j >= 0 && j < image[0].length);
  }

  function dfs(indexI, indexJ) {
    image[indexI][indexJ] = color;
    for(let i = 0; i < 4; i++) {
      if(isValid(indexI + direction[i][0], indexJ + direction[i][1]) && image[indexI + direction[i][0]][indexJ + direction[i][1]] == record) dfs(indexI + direction[i][0], indexJ + direction[i][1]);
    }
  }
  dfs(sr, sc);
  return image;
};
let image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, newColor = 2;
console.log(floodFill(image, sr, sc, newColor));
image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 2;
console.log(floodFill(image, sr, sc, newColor));
image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 0;
console.log(floodFill(image, sr, sc, newColor));
